<template>
  <view>
    <!-- 全选按钮 -->
    <view class="select-all">
      <checkbox-group @change="toggleSelectAll">
        <label>
          <checkbox :checked="isAllSelected" /> 全选
        </label>
        <button @click="clear">清除购物车</button>
      </checkbox-group>
    </view>

    <view class="product-list">
      <view v-for="item in cartItems" :key="item._id" class="product-item">
        <!-- 单个商品选择框 -->
        <checkbox-group @change="(e) => toggleSelect(item._id, e)">
          <label>
            <checkbox :value="item._id" :checked="selectedItems.includes(item._id)" />
          </label>
        </checkbox-group>

        <image class="product-image" :src="item.imgUrl" mode="aspectFill"></image>
        <view class="product-info">
          <text class="product-name">{{ item.name }}</text>
          <view class="price-container">
            <text class="current-price">¥{{ item.price }}</text>
            <text class="old-price">¥{{ item.oldPrice }}</text>
          </view>
          <text class="sales">数量 {{ item.count }}份</text>
        </view>
        <button @click="decrease(item._id)">-</button>
        <view><text>{{ item.count }}</text></view>
        <button @click="increase(item._id)">+</button>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="footer">
      <view class="total-info">
        <text>已选 {{ selectedItems.length }} 件商品</text>
        <text class="total-price">合计: ¥{{ selectedTotal }}</text>
      </view>
      <button class="submitbtn" @click="submitbtn" >去结算</button>
    </view>
  </view>
</template>

<script>
	import config from "@/Config.js";
export default {
  data() {
    return {
      cartItems: [],
      selectedItems: [], // 存储选中商品的_id
      money: 0,
      token: "",
      a:[]
      
    };
  },
  computed: {
    // 计算是否全选
    isAllSelected() {
      return this.cartItems.length > 0 &&
        this.selectedItems.length === this.cartItems.length;
    },
    // 计算选中商品总价
    selectedTotal() {
      return this.cartItems
       .filter(item => this.selectedItems.includes(item._id))
       .reduce((total, item) => total + (item.price * item.count), 0);
    }
  },
  onLoad() {
    this.token = uni.getStorageSync('token');
    this.loadCartItems();
  },
  onShow() {
    this.token = uni.getStorageSync('token');
    this.loadCartItems();
  },
  methods: {

    //去结算
    submitbtn(){
     this.a=   this.cartItems
       .filter(item => this.selectedItems.includes(item._id))
        uni.setStorageSync('a', this.a);
        uni.navigateTo({
        url: '/pages/pay/pay'
      })
       console.log(this.a)
    },
    clear() {
      this.cartItems = [];
      this.saveCartItems();
    },

    loadCartItems() {
      const allCartItems = uni.getStorageSync('cartItems') || [];
      this.cartItems = allCartItems.filter(item => item.token === this.token);
      // 初始化选中状态
      this.selectedItems = this.cartItems
       .filter(item => item.checked)
       .map(item => item._id);
    },

    // 全选/取消全选
    toggleSelectAll(e) {
      if (e.detail.value.length > 0) {
        // 全选
        this.selectedItems = this.cartItems.map(item => item._id);
        this.cartItems.forEach(item => item.checked = true);
      } else {
        // 取消全选
        this.selectedItems = [];
        this.cartItems.forEach(item => item.checked = false);
      }
      this.saveCartItems();
    },

    // 单个商品选择/取消选择
    toggleSelect(id, e) {
      const checked = e.detail.value.length > 0;
      const index = this.selectedItems.indexOf(id);

      if (checked && index === -1) {
        this.selectedItems.push(id);
      } else if (!checked && index!== -1) {
        this.selectedItems.splice(index, 1);
      }

      // 更新商品选中状态
      const item = this.cartItems.find(item => item._id === id);
      if (item) item.checked = checked;

      this.saveCartItems();
    },

    // 保存购物车数据
    saveCartItems() {
      const allCartItems = uni.getStorageSync('cartItems') || [];
      // 移除当前用户旧的购物车数据
      const otherUsersCartItems = allCartItems.filter(item => item.token!== this.token);
      // 合并当前用户更新后的购物车数据
      const newCartItems = [...otherUsersCartItems, ...this.cartItems];
      uni.setStorageSync('cartItems', newCartItems);
    },

    // 增加数量
    increase(_id) {
      this.updateCount(_id, 1);
    },

    // 减少数量
    decrease(_id) {
      this.updateCount(_id, -1);
    },

    // 更新数量
    async updateCount(_id, change) {
      try {
        const index = this.cartItems.findIndex(item => item._id === _id);

        if (index >= 0) {
          this.cartItems[index].count += change;
          if (this.cartItems[index].count <= 0) {
            this.cartItems.splice(index, 1);
            // 从选中列表中移除
            this.selectedItems = this.selectedItems.filter(id => id!== _id);
          }
        } else if (change > 0) {
          
          const product = this.cartItems.find(p => p._id === _id);
          if (product) {
            this.cartItems.push({...product, count: 1, checked: false, token: this.token });
          }
        }

        this.saveCartItems();

        // 更新服务器...
      } catch (error) {
        console.error('更新失败:', error);
      }
    },

    // 其他方法保持不变...
  }
};
</script>

<style scoped>
/* 全选样式 */
.select-all {
  padding: 20rpx;
  background: #f8f8f8;
  border-bottom: 1rpx solid #eee;
}

/* 商品列表 */
.product-list {
  padding-bottom: 120rpx; /* 为底部结算栏留出空间 */
}

.product-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin: 10rpx;
  background: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

/* 复选框样式 */
checkbox-group {
  margin-right: 20rpx;
}

/* 商品图片 */
.product-image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 8rpx;
}

/* 商品信息 */
.product-info {
  flex: 1;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.price-container {
  display: flex;
  align-items: center;
}

.current-price {
  color: #f40;
  font-size: 32rpx;
  font-weight: bold;
}

.old-price {
  color: #999;
  font-size: 24rpx;
  text-decoration: line-through;
  margin-left: 10rpx;
}

.sales {
  color: #666;
  font-size: 24rpx;
}

/* 数量加减按钮 */
.product-item button {
  width: 60rpx;
  height: 60rpx;
  margin: 0 10rpx;
  border: 1rpx solid #ddd;
  background: #f8f8f8;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 底部结算栏 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  margin-bottom: 50px;
}

.total-info {
  flex: 1;
}

.total-price {
  color: #f40;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn {
  background: #f40;
  color: #fff;
  border-radius: 40rpx;
  padding: 0 40rpx;
  height: 80rpx;
  line-height: 80rpx;
}
</style>    